<template>
  <div :class="$style.respDepartmentAdd">
    <Button type="primary" @click="showClick">{{ text }}</Button>
    <el-dialog
      :visible.sync="visible"
      :destroy-on-close="false"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeDialog"
      @opened="initFormData"
    >
      <div>
        <FormContainer :column="2">
          <el-form
            ref="form"
            :model="formData"
            :rules="formRules"
            label-width="110px"
          >

            <el-form-item prop="dept" label="责任部门">
              <CustomDictSelect
                dict-type-code="RESPONSIBLE_DEPARTMENT"
                placeholder="请选择责任部门"
                bind-name="dictName"
                bind-value="dictCode"
                filterable
                :remote="false"
                :echo-value.sync="formData.dept"
                :echo-name.sync="formData.deptName"
                :filter-handle="filterHandle"
                @on-change="deptChange"
              ></CustomDictSelect>
            </el-form-item>
            <el-form-item prop="qupOrganization" label="QUP组织">
              <SearchSelectPicker
                :url="'/call-center/api/v1/staffInfo/remoteOrg/' + formData.dept + '/page'"
                placeholder="请选择QUP组织"
                lable-name="orgName"
                value-name="orgCode"
                :readonly="!formData.dept"
                :must-pid="true"
                :parent-id="formData.dept"
                :lable.sync="formData.qupOrganizationName"
                :value.sync="formData.qupOrganization"
                @selectChange="orgChange"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="receiver" label="用户">
              <SearchSelectPicker
                :url="'/call-center/api/v1/staffInfo/user/org/' + formData.qupOrganization"
                placeholder="请选择用户"
                lable-name="userName"
                value-name="account"
                :readonly="!formData.qupOrganization"
                :must-pid="true"
                :parent-id="formData.qupOrganization"
                :value.sync="formData.receiver"
                :lable.sync="formData.receiverName"
                @selectChange="receiverChange"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="receiverPhone" label="联系电话">
              <el-input v-model="formData.receiverPhone" clearable placeholder="请输入联系电话" :maxlength="11" />
            </el-form-item>

            <!-- <el-form-item prop="platformCodes" label="电商平台" :span="24">
              <SearchSelectPicker
                url="/select-service/api/v1/eco/platform/page"
                placeholder="请选择电商平台"
                lable-name="name"
                value-name="code"
                multiple
                filterable
                :value.sync="formData.platformCodes"
                @selectChange="handlePlatformMultiChange"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="platformStoreCodes" label="电商店铺" :span="24">
              <SearchSelectPicker
                url="/select-service/api/v1/eco/shop/page"
                placeholder="请选择电商店铺"
                lable-name="name"
                value-name="code"
                :disabled="!formData.platformCodes"
                :parent-id="formData.platformCodes"
                :must-pid="true"
                multiple
                filterable
                :params="{
                  query:{
                    platformCode:{
                      operator:'in',
                      value:formData.platformCodes
                    }
                  },
                  type:0
                }"
                :value.sync="formData.platformStoreCodes"
                @selectChange="handleMultiStoreChange"
              ></SearchSelectPicker>
            </el-form-item>
            <el-form-item prop="postCode" label="岗位" :span="24">
              <CustomDictSelect
                dict-type-code="DEPT_POST_CODE"
                placeholder="请选择岗位"
                bind-name="dictName"
                bind-value="dictCode"
                :multiple="true"
                filterable
                :collapse-tags="false"
                clear
                :remote="false"
                :echo-value.sync="formData.postCode"
                :echo-name.sync="formData.postName"
              ></CustomDictSelect>
            </el-form-item> -->
            <el-form-item label="启用状态">
              {{ formData.state?'启用':'停用' }}
            </el-form-item>
            <el-form-item prop="remark" label="备注" :span="24">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="2"
                clearable
                placeholder="请输入备注"
              />
            </el-form-item>
            <el-form-item align="right" :span="24">
              <Button @click="closeDialog">取消</Button>
              <Button type="primary" :loading="loading" @click="submitHandle">确定</Button>
            </el-form-item>
          </el-form>
        </FormContainer>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import CustomDictSelect from '@/components/CustomDictSelect'
import { saveDeptReceiver } from '@/api/workOrderDeptReceiver'

export default {
  name: 'RespDepartmentAdd',
  components: {
    FormContainer,
    Button,
    SearchSelectPicker,
    CustomDictSelect
  },
  props: {
    row: {
      type: Object,
      default: () => ({})
    },
    text: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      storeFilter: [], // 电商店铺查询条件
      formData: {
        dept: '',
        deptName: '',
        qupOrganization: '',
        qupOrganizationName: '',
        receiver: '',
        receiverName: '',
        receiverPhone: '',
        platformCodes: [],
        platformName: [],
        platformList: [],
        platformStoreCodes: [],
        platformStoreName: [],
        platformStoreList: [],
        postCode: [],
        postName: '',
        remark: '',
        state: 1
      },
      formRules: {
        dept: [
          { required: true, message: '责任部门不能为空', trigger: 'change' }
        ],
        qupOrganization: [
          { required: true, message: '组织不能为空', trigger: 'change' }
        ],
        receiver: [
          { required: true, message: '用户不能为空', trigger: 'change' }
        ],
        receiverPhone: [
          { required: true, message: '联系电话不能为空', trigger: ['change', 'blur'] },
          { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: '请输入正确的手机号码', trigger: ['change', 'blur'] }
        ]
        /* platformCodes: [
          { required: true, message: '电商平台不能为空', trigger: 'change' }
        ],
        platformStoreCodes: [
          { required: true, message: '电商店铺不能为空', trigger: 'change' }
        ],
        postCode: [
          { required: true, message: '岗位不能为空', trigger: 'change' }
        ] */
      }
    }
  },
  computed: {
    isEdit() {
      return Object.keys(this.row).length > 0
    }
  },
  methods: {
    showClick() {
      if (this.text === '编辑' && Object.keys(this.row).length === 0) {
        this.$message({
          message: '请选择需编辑项',
          type: 'warning'
        })
        return
      }
      this.visible = true
    },
    // 过滤掉电商管理部
    filterHandle(data) {
      const exclude = ['XN03005200']
      return data.filter(e => !exclude.includes(e.dictCode))
    },
    // 责任部门变更
    deptChange(data) {
      this.$set(this.formData, 'qupOrganization', '')
      this.$set(this.formData, 'qupOrganizationName', '')
      this.orgChange()
      // setTimeout(() => { this.$refs['form'].validateField(['qupOrganization']) }, 0)
    },
    // qup组织变更
    orgChange(data) {
      this.$set(this.formData, 'receiver', '')
      this.$set(this.formData, 'receiverName', '')
    },
    // 用户选择
    receiverChange(data) {
      const phone = data && data.phone
      if (phone) {
        this.$set(this.formData, 'receiverPhone', phone)
      }
    },
    // 平台多选变更
    handlePlatformMultiChange(data) {
      this.$set(this.formData, 'platformList', data || [])

      this.$set(this.formData, 'platformStoreCodes', [])
      this.$set(this.formData, 'platformStoreList', [])
    },
    // 店铺多选变更
    handleMultiStoreChange(data) {
      this.$set(this.formData, 'platformStoreList', data || [])
    },
    // 岗位改变是验证
    postChange(data) {
      setTimeout(() => { this.$refs['form'].validateField(['postCode']) }, 0)
    },
    // 增加、修改
    submitHandle() {
      if (this.loading) return
      this.$refs.form.validate().then(() => {
        this.loading = true
        const params = { ...this.formData }
        params.platformList = this.formData.platformList.map(v => {
          return {
            platformCode: v.code,
            platformName: v.name
          }
        })
        params.platformStoreList = this.formData.platformStoreList.map(v => {
          return {
            storeCode: v.code,
            storeName: v.name
          }
        })
        delete params.platformCodes
        delete params.platformStoreCodes
        params.postCode = this.formData.postCode && this.formData.postCode.length > 0 ? this.formData.postCode.join(',') : ''
        if (this.isEdit) {
          params.id = this.row.id
        }
        saveDeptReceiver(params).then(res => {
          this.loading = false
          if (res.success === 1) {
            this.$message.success('保存成功')
            this.$emit('on-success', !this.isEdit)
            this.closeDialog()
          }
        }).catch(() => {
          this.loading = false
        })
      })
    },
    clearForm() {
      for (const key of Object.keys(this.formData)) {
        if (['platformList', 'platformStoreList', 'platformCodes', 'platformStoreCodes'].includes(key)) {
          this.$set(this.formData, key, [])
        } else {
          this.$set(this.formData, key, key === 'state' ? 1 : '')
        }
      }
      this.storeFilter = []
      this.$refs.form && this.$refs.form.clearValidate()
      this.$refs.form && this.$refs.form.resetFields()
    },
    closeDialog() {
      this.clearForm()
      this.visible = false
    },
    initFormData() {
      for (const key of Object.keys(this.formData)) {
        if (['platformList', 'platformStoreList', 'platformCodes', 'platformStoreCodes', 'postCode'].includes(key)) {
          this.$set(this.formData, key, [])
        } else {
          this.$set(this.formData, key, key === 'state' ? 1 : '')
        }
      }
      if (this.isEdit) {
        const row = { ...this.row }
        for (const key of Object.keys(this.formData)) {
          if (!['platformList', 'platformStoreList', 'platformCodes', 'platformStoreCodes', 'postCode'].includes(key)) {
            this.$set(this.formData, key, row[key] || '')
          }
        }
        // 平台
        let platformList = []
        const platformCodes = []
        if (row.platformList && row.platformList.length) {
          platformList = row.platformList.map(v => {
            platformCodes.push(v.platformCode)
            return {
              name: v.platformName,
              code: v.platformCode
            }
          })
        }
        this.$set(this.formData, 'platformList', platformList)
        this.$set(this.formData, 'platformCodes', platformCodes)

        // 店铺
        let platformStoreList = []
        const platformStoreCodes = []
        if (row.platformStoreList && row.platformStoreList.length) {
          platformStoreList = row.platformStoreList.map(v => {
            platformStoreCodes.push(v.storeCode)
            return {
              name: v.storeName,
              code: v.storeCode
            }
          })
        }
        this.$set(this.formData, 'platformStoreList', platformStoreList)
        this.$set(this.formData, 'platformStoreCodes', platformStoreCodes)
        if (row.postCode && row.postCode.length > 0) {
          const postCode = row.postCode.split(',')
          this.$set(this.formData, 'postCode', postCode)
        }

        this.$set(this.formData, 'state', row.state)
      } else {
        this.$set(this.formData, 'state', 1)
      }

      /* if (this.formData.platformCodes) {
        this.storeFilter = [{
          id: 'platformCode',
          property: 'platformCode',
          operator: 'in',
          value: `[${this.formData.platformCodes}]`
        }]
      } else {
        this.storeFilter = []
      } */
    }
  }
}
</script>
<style lang="scss" module>
.respDepartmentAdd {

}
</style>
